<?php
/**
 * Pert PHP Library
 * User Class
 *
 * @author	Emre Hasegeli <hasegeli@gmail.com>
 * @license	GNU General Public License v3
 */

namespace Pert;

require_once __DIR__ . '/Client.php';

class User extends Client
{
	protected $id;

	protected function __construct($id)
	{
		parent::__construct();

		$this->id = $id;
	}

	private static $session;

	private static function session()
	{
		if(!isset(self::$session))
			self::$session = session_start();

		return self::$session;
	}

	public static function Get()
	{
		self::session();

		if(isset($_SESSION['Id']))
			if(isset($_SESSION['Password']))
			{
				if(!(parent::Get() instanceof self))
					new self($_SESSION['Id']);

				return parent::Get();
			}
	}

	final public function Id()
	{
		return $this->id;
	}

	public function __ToString()
	{
		return $this->id;
	}

	protected function password()
	{
		self::session();

		return $_SESSION['Password'];
	}

	protected static function passwordGeneralAvailability($password)
	{
		if(strlen($password) < 4)
			return false;

		return true;
	}

	protected function passwordAvailability($password)
	{
		if(!self::passwordGeneralAvailability($password))
			return false;

		if($password == $this->password())
			return false;

		return true;
	}

	public function SelectLanguage()
	{
		self::session();

		if(empty($_SESSION['Language']))
			$_SESSION['Language'] = parent::SelectLanguage()->Id();

		require_once __DIR__ . '/Language.php';

		return Language::Select($_SESSION['Language']);
	}

	public static function Login($id,
			$password)
	{
		if(!self::passwordGeneralAvailability($password))
			return false;

		self::session();

		$_SESSION['Id'] = (string) $id;

		$_SESSION['Password'] = md5($password);

		return true;
	}

	public function Logout()
	{
		self::session();

		unset($_SESSION['Id']);

		unset($_SESSION['Password']);

		unset($this);

		return true;
	}
}
